﻿// Decompiled with JetBrains decompiler
// Type: cXMLWizard.CUiLayerExpander
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.OLPEditor.cXMLWizard.Resources;
using LayersParser.Extensions;
using LayersParser.Interfaces;
using LayersParser.Objects;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Olp;


namespace cXMLWizard;

public class CUiLayerExpander : UserControl
{
  private IContainer components;
  private ToolStrip toolStrip1;
  private ToolStripLabel nameOfLayer;
  private RichTextBox richtextbox;
  private ContextMenuStrip contextMenuStrip;
  private ToolStripMenuItem propagateToolStripMenuItem;
  private ToolStripMenuItem editNewParameterToolStripMenuItem;
  private ToolStripMenuItem fromNameToolStripMenuItem;
  private ToolStripMenuItem fromValueToolStripMenuItem;
  private ListBox intelliSenseListBox;
  private ToolStripButton help;
  private List<string> parametersDictionary = new List<string>();
  private TxRobot txRobot;
  private TxOlpControllerUtilities controllerUtilities = new TxOlpControllerUtilities();
  private Command command;
  private Layers lastLayerClicked;
  private ToolTip toolTip = new ToolTip();
  private ToolTip conditiontooltip = new ToolTip();
  private int bufferIndex;
  private List<Param> parameters = new List<Param>();
  private List<string> ISList = new List<string>((IEnumerable<string>) new string[133]
  {
    "# Abort",
    "# BlankMfg",
    "# BlankPath <opName>",
    "# CallPath <varName>",
    "# CallToolPath <opName> <toolName>",
    "# ClosePaintGun",
    "# Destination <robotName>",
    "# Destination <deviceName>",
    "# Destination <gripperName>",
    "# DisplayMfg",
    "# DisplayPath <opName>",
    "# DriveDevicesSynch <dev1>:<pos1> <dev2>:<pos2>",
    "# DriveDevicesAsynch <dev1>:<pos1> <dev2>:<pos2>",
    "# Error <message>",
    "# ExitCycle",
    "# FormatDataVariable <TargetData> <StringFormat> <InputVar1> <InputVar2>",
    "# GetIntRobotStudyParam <outVar> <robotName> <paramName> <expression>",
    "# Grip <gripper>",
    "# GunToState",
    "# IsValidRoboticOperation <outBool> <opName>",
    "# IsValidRoboticProgram <outBool> <progName>",
    "# IsValidRobotModuleProcedure <outBool> <procName>",
    "# JumpDeviceJoints <device> <j1>:<val1> <j2>:<val2>",
    "# Move",
    "# Note <message>",
    "# OpenPaintGun",
    "# Pause",
    "# PerfoStart <CounterName>",
    "# PerfoStop <CounterName>",
    "# Pulse <signal> <duration>",
    "# Send <signal> <value>",
    "# SetDataVariable <TargetData> <OriData>",
    "# SetGunClosePose <GunName> <PoseName>",
    "# SetIntRobotStudyParam <outVar> <robotName> <paramName>",
    "# SetSignal <signal> <expression>",
    "# SetVariable <var> <expression>",
    "# WaitDevice <pos>",
    "# WaitReached",
    "# WaitSignal <signal> <value>",
    "# WaitSignals <expression>",
    "# WaitSignalsFlyBy <expression>",
    "# WaitTime <duration>",
    "# Warning <message> # Weld start the welding simulation",
    "# If <condition> Then",
    "# Elsif <condition> Then",
    "# Endif",
    "# For <var> From <start> To <end> Step <step> Do",
    "# For <var> From <start> To <end> Do",
    "# Endfor",
    "# While <expression> Do",
    "# Endwhile",
    "# Switch <expression>",
    "# Case <val1>, <val2>",
    "# Default",
    "# Endswitch",
    "# Label <label>",
    "# Goto <label>",
    "# Break",
    "# MathAbs <varName> <value>",
    "# MathSqrt <varName> <value>",
    "# SetVariable <stringVariableDst>  <stringSrc1> + <stringSrc2>",
    "# SetVariable <stringVariableDst> <stringSrc>[<index>]",
    "# StrLen <intVariableLength> <string>",
    "# StrToInt <boolVariableResult> <intVariableValue> <string>",
    "# StrToReal <boolVariableResult> <realVariableValue> <string>",
    "# StrFromReal <realVariableValue>",
    "# StrChr <intVariablePos> <intStartWith1> <stringText> <stringListofChars> <TRUE/FALSE>",
    "# StrCmp <boolVariableResult> <string1> <string2>",
    "# StrStr <intVariablePos> <intStartWith1> <stringText> <stringSearch>",
    "# StrIStr <intVariablePos> <intStartWith1> <stringText> <stringSearch>",
    "# VectorAdd <ResVec> <Vec1> <Vec2>",
    "# VectorCrossProd <ResVec> <Vec1> <Vec2>",
    "# VectorDotProd <ResVar> <Vec1> <Vec2>",
    "# VectorInit <ResVec> <X> <Y> <Z>",
    "# VectorInitFromTransformationColumn <ResVec> <Tr1> <ColIndex>",
    "# VectorNormalize <ResVec> <Vec1>",
    "# VectorScale <ResVec> <Factor> <Vec1>",
    "# VectorSub <ResVec> <Vec1> <Vec2>",
    "# TransformationInit <ResTr> <X> <Y> <Z> <RX> <RY> <RZ> [<OriMode>]",
    "# TransformationInitFromLocationAbsolutePosition <ResTr> <LocName>",
    "# TransformationInitFromLocationRelativePosition <ResTr> <LocName>",
    "# TransformationInitFromObj <ResTr> <ObjectName>",
    "# TransformationInitFromRobotSystemFrame <ResTr> <RobotSystemFrameName>",
    "# TransformationInv <ResTr> <Tr1>",
    "# TransformationMult <ResTr> <Tr1> <Tr2>",
    "# TransformationMultVec <ResTr> <Tr1> <Vec>",
    "# TransformationRel <ResTr> <RefTr> <TgtTr>",
    "# RelocateLocationAbsolutePosition <LocName> <TransformationMatrixVarName>",
    "# RelocateLocationRelativePosition <LocName> <TransformationMatrixVarName>",
    "# RelocateObj <ObjectName> <TransformationMatrixVarName>",
    "# RelocateRobotSystemFrame <RobotSystemFrameName> <TransformationMatrixVarName>",
    "# MoveRelBase [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveJRelBase  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveLRelBase  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveCRelBase  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveRelTool  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveJRelTool [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveLRelTool  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveCRelTool  [<RefLoc>] <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveRelFrame  <Reframe> <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveJRelFrame <Reframe> <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveLRelFrame <Reframe> <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveCRelFrame <Reframe> <X> <Y> <Z> [<RX> <RY'> <RZ> [<OriMode>]]",
    "# MoveRelBase <X> <Y> <Z> [Speed = 250] [Zone = medium]",
    "# MoveRelBase 500 0 0 [Attachment =] [Ext1=50]",
    "# MoveRelBase 500 0 0 [Attachment = null] [Ext1 = 50]",
    "# MoveRelBase 500 0 0 [Attachment = stn1.k2] [Ext1 = 50]",
    "# MoveWithAsgStudDynamicTcp <Weld Frame number :1-4> [ Zone = fine]",
    "# ModifyRcsData <ParamId> <ParamValue>",
    "# GetRcsData <ResVariable> <ParamId>",
    "${Robot}",
    "${ActiveGun}",
    "${ActiveGunMainJoint}",
    "${ActiveGunBalancingJoint}",
    "${ActiveGripper}",
    "${ActiveGunMainJointValue:<PoseName>}",
    "${ActiveGunBalancingJointValue:<PoseName>}",
    "${IsActiveGunTypeX}",
    "${AutoTeach}",
    "${MoveToSingleLocation}",
    "${LineSimulation}",
    "${Robot.Tcpf.X}",
    "${Robot.Tcpf.Y}",
    "${Robot.Tcpf.Z}",
    "${Robot.Tcpf.RPY_X}",
    "${Robot.Tcpf.RPY_RY}",
    "${Robot.Tcpf.RPY_RZ}",
    "${Robot.Ext}",
    "${CurrentSimulationTime}",
    "${UserName}",
    "${Date}",
    "${Time}",
    "${ConveyorPositionSignal}"
  });
  private object parent;
  private bool isExpanded;
  private int expanded;
  private int collapsed = 30;
  private bool intelliSenseListBoxVisible = true;

  protected override void Dispose(bool disposing)
  {
    if (disposing && this.components != null)
      this.components.Dispose();
    base.Dispose(disposing);
  }

  private void InitializeComponent()
  {
    this.components = (IContainer) new System.ComponentModel.Container();
    ComponentResourceManager componentResourceManager = new ComponentResourceManager(typeof (CUiLayerExpander));
    this.toolStrip1 = new ToolStrip();
    this.nameOfLayer = new ToolStripLabel();
    this.help = new ToolStripButton();
    this.richtextbox = new RichTextBox();
    this.contextMenuStrip = new ContextMenuStrip(this.components);
    this.propagateToolStripMenuItem = new ToolStripMenuItem();
    this.editNewParameterToolStripMenuItem = new ToolStripMenuItem();
    this.fromNameToolStripMenuItem = new ToolStripMenuItem();
    this.fromValueToolStripMenuItem = new ToolStripMenuItem();
    this.intelliSenseListBox = new ListBox();
    this.toolStrip1.SuspendLayout();
    this.contextMenuStrip.SuspendLayout();
    this.SuspendLayout();
    this.toolStrip1.GripStyle = ToolStripGripStyle.Hidden;
    this.toolStrip1.Items.AddRange(new ToolStripItem[2]
    {
      (ToolStripItem) this.nameOfLayer,
      (ToolStripItem) this.help
    });
    this.toolStrip1.Location = new Point(0, 0);
    this.toolStrip1.Name = "toolStrip1";
    this.toolStrip1.Size = new Size(400, 25);
    this.toolStrip1.TabIndex = 0;
    this.toolStrip1.Text = "toolStrip1";
    this.toolStrip1.Click += new EventHandler(this.Expand);
    this.nameOfLayer.Name = "nameOfLayer";
    this.nameOfLayer.Size = new Size(78, 22);
    this.nameOfLayer.Text = "nameOfLayer";
    this.help.DisplayStyle = ToolStripItemDisplayStyle.Image;
    this.help.Image = (Image) componentResourceManager.GetObject("Information");
    this.help.ImageTransparentColor = Color.Magenta;
    this.help.Name = "help";
    this.help.Size = new Size(23, 22);
    this.help.ToolTipText = cXMLWizardStringTable.TOOLTIP_HELP;
    this.richtextbox.ContextMenuStrip = this.contextMenuStrip;
    this.richtextbox.Location = new Point(5, 30);
    this.richtextbox.Name = "richtextbox";
    this.richtextbox.Size = new Size(390, 360);
    this.richtextbox.TabIndex = 1;
    this.richtextbox.Text = "";
    this.richtextbox.WordWrap = false;
    this.richtextbox.TextChanged += new EventHandler(this.Layer_TextChanged);
    this.richtextbox.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
    this.richtextbox.MouseDown += new MouseEventHandler(this.Layer_MouseDown);
    this.richtextbox.MouseMove += new MouseEventHandler(this.Layer_MouseMove);
    this.contextMenuStrip.Items.AddRange(new ToolStripItem[2]
    {
      (ToolStripItem) this.propagateToolStripMenuItem,
      (ToolStripItem) this.editNewParameterToolStripMenuItem
    });
    this.contextMenuStrip.Name = "contextMenuStrip";
    this.contextMenuStrip.Size = new Size(177, 70);
    this.propagateToolStripMenuItem.Name = "propagateToolStripMenuItem";
    this.propagateToolStripMenuItem.Size = new Size(176 /*0xB0*/, 22);
    this.editNewParameterToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[2]
    {
      (ToolStripItem) this.fromNameToolStripMenuItem,
      (ToolStripItem) this.fromValueToolStripMenuItem
    });
    this.editNewParameterToolStripMenuItem.Name = "editNewParameterToolStripMenuItem";
    this.editNewParameterToolStripMenuItem.Size = new Size(176 /*0xB0*/, 22);
    this.editNewParameterToolStripMenuItem.Text = cXMLWizardStringTable.EDIT_NEW_PARAMETER_NAME;
    this.fromNameToolStripMenuItem.Name = "fromNameToolStripMenuItem";
    this.fromNameToolStripMenuItem.Size = new Size(138, 22);
    this.fromNameToolStripMenuItem.Text = cXMLWizardStringTable.FROM_NAME_LABEL;
    this.fromNameToolStripMenuItem.Click += new EventHandler(this.EditNewParameter);
    this.fromValueToolStripMenuItem.Name = "fromValueToolStripMenuItem";
    this.fromValueToolStripMenuItem.Size = new Size(138, 22);
    this.fromValueToolStripMenuItem.Text = cXMLWizardStringTable.FROM_VALUE_LABEL;
    this.fromValueToolStripMenuItem.Click += new EventHandler(this.EditNewParameter);
    this.intelliSenseListBox.FormattingEnabled = true;
    this.intelliSenseListBox.Location = new Point(46, 62);
    this.intelliSenseListBox.Name = "intelliSenseListBox";
    this.intelliSenseListBox.Size = new Size(120, 95);
    this.intelliSenseListBox.TabIndex = 2;
    this.AutoScaleDimensions = new SizeF(6f, 13f);
    this.AutoScaleMode = AutoScaleMode.Font;
    this.Controls.Add((System.Windows.Forms.Control) this.intelliSenseListBox);
    this.Controls.Add((System.Windows.Forms.Control) this.richtextbox);
    this.Controls.Add((System.Windows.Forms.Control) this.toolStrip1);
    this.Name = "LayerExpander";
    this.Size = new Size(400, 400);
    this.ClientSizeChanged += new EventHandler(this.Expansion);
    this.toolStrip1.ResumeLayout(false);
    this.toolStrip1.PerformLayout();
    this.contextMenuStrip.ResumeLayout(false);
    this.ResumeLayout(false);
    this.PerformLayout();
  }

  public CUiLayerExpander()
  {
    this.InitializeComponent();
    this.expanded = this.Size.Height - 40;
    this.intelliSenseListBox.Parent = (System.Windows.Forms.Control) this;
    this.intelliSenseListBox.KeyUp += new KeyEventHandler(this.OnKeyUp);
    this.intelliSenseListBox.DoubleClick += new EventHandler(this.IntelliSenseDoubleClick);
    this.intelliSenseListBox.Visible = false;
  }

  private void IntelliSenseDoubleClick(object sender, EventArgs e)
  {
    int selectionStart = this.richtextbox.SelectionStart;
    if (((ListBox) sender).SelectedItem.ToString().Contains("#") || ((ListBox) sender).SelectedItem.ToString().Contains("$"))
    {
      this.richtextbox.Text = this.richtextbox.Text.Remove(this.richtextbox.Text.LastIndexOf(this.GetLastString(true))) + ((ListBox) sender).SelectedItem.ToString();
    }
    else
    {
      string lastString = this.GetLastString(false);
      this.lastLayerClicked.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
      if (this.lastLayerClicked.Node.Name == (XName) "DownloadLayer")
      {
        this.command.UILayer.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
        ((CUiMainwindow) this.parent).UILayer.RichTextBox.Text = this.command.UILayer.DetailledCommand;
        this.command.SimulationLayer.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
        ((CUiMainwindow) this.parent).SimulationLayer.RichTextBox.Text = this.command.SimulationLayer.DetailledCommand;
      }
      this.richtextbox.Text = this.lastLayerClicked.DetailledCommand;
      this.SetColors(this.richtextbox, this.lastLayerClicked);
    }
    this.richtextbox.SelectionStart = this.richtextbox.Text.Length - 1;
    this.intelliSenseListBox.Hide();
  }

  public List<Param> Parameters
  {
    get => this.parameters;
    set => this.parameters = value;
  }

  public TxRobot TxRobot
  {
    get => this.txRobot;
    set => this.txRobot = value;
  }

  private Point GetCaretPos()
  {
    return this.richtextbox.GetPositionFromCharIndex(this.richtextbox.SelectionStart);
  }

  public RichTextBox RichTextBox
  {
    get => this.richtextbox;
    set => this.richtextbox = value;
  }

  private string GetLastString(bool WithOrWithoutWhitespace)
  {
    int length = 0;
    int selectionStart = this.richtextbox.SelectionStart;
    string lastString = "";
    if (WithOrWithoutWhitespace)
    {
      if (this.richtextbox.Text != "")
        length = selectionStart + this.TakeNextWord(selectionStart);
      int startIndex = this.richtextbox.Text.Substring(0, length).LastIndexOf("#");
      List<string> stringList = new List<string>();
      if (startIndex != -1)
        lastString = this.richtextbox.Text.Substring(startIndex, length - startIndex).Replace("\n", "");
    }
    else
    {
      string[] strArray = this.richtextbox.Text.Substring(0, !(this.richtextbox.Text != "") ? 0 : selectionStart + this.TakeNextWord(selectionStart)).Split(' ');
      lastString = strArray[strArray.Length - 1].Replace("\n", "");
    }
    return lastString;
  }

  private int TakeNextWord(int index)
  {
    int nextWord = 0;
    bool flag = false;
    while (index + nextWord != this.richtextbox.Text.Length && !flag)
    {
      if (this.richtextbox.Text.ToCharArray()[index + nextWord] != ' ')
        ++nextWord;
      else
        flag = !flag;
    }
    return nextWord;
  }

  private void OnKeyPress(object sender, KeyPressEventArgs e)
  {
    this.OnKeyPress(e);
    if (e.KeyChar == '\r')
    {
      if (this.intelliSenseListBox.Visible)
      {
        this.intelliSenseListBox.Focus();
      }
      else
      {
        this.intelliSenseListBoxVisible = false;
        int selectionStart = this.richtextbox.SelectionStart;
        this.richtextbox.Text = $"{this.richtextbox.Text.Substring(0, selectionStart)}\n{this.richtextbox.Text.Substring(selectionStart)}";
        this.richtextbox.Select(selectionStart + 1, 0);
        this.intelliSenseListBoxVisible = true;
      }
      e.Handled = true;
    }
    else
    {
      if (e.KeyChar != '\u001B')
        return;
      this.intelliSenseListBox.Visible = false;
      e.Handled = true;
    }
  }

  private void OnKeyUp(object sender, KeyEventArgs e)
  {
    int selectionStart = this.richtextbox.SelectionStart;
    if (e.KeyCode == Keys.Return && (((ListBox) sender).SelectedItem.ToString().Contains("#") || ((ListBox) sender).SelectedItem.ToString().Contains("$")))
      this.richtextbox.Text = this.richtextbox.Text.Remove(this.richtextbox.Text.LastIndexOf(this.GetLastString(true))) + ((ListBox) sender).SelectedItem.ToString();
    else if (e.KeyCode == Keys.Return)
    {
      string lastString = this.GetLastString(false);
      this.richtextbox.Text.Remove(this.richtextbox.Text.LastIndexOf(lastString));
      if (this.lastLayerClicked.Node.Name == (XName) "DownloadLayer")
      {
        this.command.UILayer.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
        ((CUiMainwindow) this.parent).UILayer.RichTextBox.Text = this.command.UILayer.DetailledCommand;
        this.command.SimulationLayer.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
        ((CUiMainwindow) this.parent).SimulationLayer.RichTextBox.Text = this.command.SimulationLayer.DetailledCommand;
      }
      this.lastLayerClicked.ChangeItems(this.richtextbox.SelectionStart, lastString, ((ListBox) sender).SelectedItem.ToString());
      this.richtextbox.Text = this.lastLayerClicked.DetailledCommand;
      this.SetColors(this.richtextbox, this.lastLayerClicked);
    }
    this.richtextbox.SelectionStart = selectionStart;
    this.intelliSenseListBox.Hide();
  }

  public void LayerExpanderCtor(Command newcommand, Layers layer)
  {
    this.command = newcommand;
    this.lastLayerClicked = layer;
    this.richtextbox.Text = layer.DetailledCommand;
    this.bufferIndex = this.richtextbox.Text.Length;
    this.parameters = newcommand.Params;
    this.lastLayerClicked.Params = this.parameters.ParToStr();
    this.SetColors(this.richtextbox, this.lastLayerClicked);
  }

  public object Control
  {
    get => this.parent;
    set => this.parent = value;
  }

  private ISublines GiveSubline(RichTextBox richTextBox, Point point, Layers layer)
  {
    int indexFromPosition = richTextBox.GetCharIndexFromPosition(point);
    int index = 0;
    foreach (Line line in layer.Multiline)
    {
      foreach (ISublines sublines in line.Items)
      {
        if ((sublines.Bounds[0] != 0 || sublines.Bounds[1] != 0) && indexFromPosition >= sublines.Bounds[0] && indexFromPosition < sublines.Bounds[1])
          return layer.SetItem(sublines.Value, index);
      }
      ++index;
    }
    return (ISublines) null;
  }

  private void SetColors(RichTextBox richTextBox, Layers layer)
  {
    int selectionStart = richTextBox.SelectionStart;
    int start = 0;
    this.bufferIndex = this.richtextbox.Text.Length;
    int index = 0;
    foreach (Line line in layer.Multiline)
    {
      foreach (ISublines sublines in line.Items)
      {
        string str = sublines.Value;
        if (str != "" && str != null && richTextBox.Lines.Length > index)
        {
          if (sublines is IfCondition)
          {
            if (richTextBox.Lines[index].Contains(str))
            {
              int length = str.Length;
              richTextBox.Select(richTextBox.Find(str, start, RichTextBoxFinds.None), length);
              richTextBox.SelectionColor = Color.Purple;
              List<int> intList = new List<int>()
              {
                richTextBox.Find(str, start, RichTextBoxFinds.None),
                richTextBox.Find(str, start, RichTextBoxFinds.None) + length
              };
              sublines.Bounds = intList;
            }
          }
          else if (sublines.ReturnConditionType() == "dynamicParameter")
          {
            if (richTextBox.Lines[index].Contains(str))
            {
              int length = str.Length;
              richTextBox.Select(richTextBox.Find(str, start, RichTextBoxFinds.None), length);
              richTextBox.SelectionColor = Color.Brown;
              List<int> intList = new List<int>()
              {
                richTextBox.Find(str, start, RichTextBoxFinds.None),
                richTextBox.Find(str, start, RichTextBoxFinds.None) + length
              };
              sublines.Bounds = intList;
            }
          }
          else if (sublines.ReturnConditionType() == "parameter")
          {
            if (richTextBox.Lines[index].Contains(str))
            {
              int length = str.Length;
              richTextBox.Select(richTextBox.Find(str, start, RichTextBoxFinds.None), length);
              richTextBox.SelectionColor = Color.Red;
              List<int> intList = new List<int>()
              {
                richTextBox.Find(str, start, RichTextBoxFinds.None),
                richTextBox.Find(str, start, RichTextBoxFinds.None) + length
              };
              sublines.Bounds = intList;
            }
          }
          else if (sublines.ReturnConditionType() == "expression")
          {
            if (richTextBox.Lines[index].Contains(str))
            {
              int length = str.Replace("'", "").Length;
              richTextBox.Select(richTextBox.Find(str.Replace("'", ""), start, RichTextBoxFinds.None), length);
              richTextBox.SelectionColor = Color.Green;
              List<int> intList = new List<int>()
              {
                richTextBox.Find(str, start, RichTextBoxFinds.None),
                richTextBox.Find(str, start, RichTextBoxFinds.None) + length
              };
              sublines.Bounds = intList;
            }
          }
          else if (richTextBox.Lines[index].Contains(str))
          {
            int length = str.Length;
            richTextBox.Select(richTextBox.Find(str, start, RichTextBoxFinds.None), length);
            richTextBox.SelectionColor = Color.Black;
            List<int> intList = new List<int>()
            {
              richTextBox.Find(str, start, RichTextBoxFinds.None),
              richTextBox.Find(str, start, RichTextBoxFinds.None) + length
            };
            sublines.Bounds = intList;
          }
          if (richTextBox.Lines[index].Contains(str))
            start = richTextBox.Find(str, start, RichTextBoxFinds.None);
        }
      }
      ++index;
    }
    richTextBox.Select(selectionStart, 0);
  }

  public string NameOfLayer
  {
    set => this.nameOfLayer.Text = value;
  }

  public bool IsExpanded
  {
    get => this.isExpanded;
    set
    {
      this.isExpanded = value;
      if (value)
        this.Size = new Size(this.Size.Width, this.expanded);
      else
        this.Size = new Size(this.Size.Width, this.collapsed);
    }
  }

  private void Expand(object sender, EventArgs e) => this.IsExpanded = !this.isExpanded;

  private void Expansion(object sender, EventArgs e)
  {
    Size size1;
    ref Size local = ref size1;
    Size size2 = this.Size;
    int width = size2.Width - 10;
    size2 = this.Size;
    int height = size2.Height - 40;
    local = new Size(width, height);
    this.richtextbox.Size = size1;
  }

  private void Layer_TextChanged(object sender, EventArgs e)
  {
    if (this.bufferIndex == this.richtextbox.Text.Length || !this.intelliSenseListBoxVisible)
      return;
    List<string> stringList = new List<string>();
    Point caretPos = this.GetCaretPos();
    this.intelliSenseListBox.SetBounds(caretPos.X + this.richtextbox.Left, caretPos.Y + this.richtextbox.Top + 20, 150, 50);
    if (this.lastLayerClicked.Node.Name == (XName) "DownloadLayer")
    {
      ((CUiMainwindow) this.parent).UILayer.RichTextBox.Text = this.RichTextBox.Text;
      ((CUiMainwindow) this.parent).SimulationLayer.RichTextBox.Text = this.RichTextBox.Text;
    }
    this.lastLayerClicked.SetNewConst(this.richtextbox);
    this.SetColors(this.richtextbox, this.lastLayerClicked);
    if (this.lastLayerClicked.Node.Name == (XName) "UILayer" || this.lastLayerClicked.Node.Name == (XName) "DownloadLayer")
      ((CUiMainwindow) this.parent).IsDisabled = this.richtextbox.Text.Length == 0 || this.command.Name == "" || this.command.Name == null;
    string strPar = this.GetLastString(false);
    if (strPar != "")
    {
      List<string> source = new List<string>();
      foreach (string key in (IEnumerable) this.controllerUtilities.GetControllerComplexParameters((ITxRobotController) this.txRobot.Controller).Keys)
        source.Add(key);
      this.command.UILayer.DynamicParameters = this.command.SimulationLayer.DynamicParameters = this.command.DownloadLayer.DynamicParameters = source;
      foreach (string str in source.Where<string>((Func<string, bool>) (n => n.StartsWith(strPar.ToUpper(), true, (CultureInfo) null))).Select<string, string>((Func<string, string>) (r => r)))
        stringList.Add(str);
    }
    if (stringList.Count != 0)
    {
      this.intelliSenseListBox.DataSource = (object) stringList;
      this.intelliSenseListBox.Show();
    }
    else
      this.intelliSenseListBox.Hide();
  }

  private void Layer_MouseMove(object sender, MouseEventArgs e)
  {
    string caption = "";
    if (this.richtextbox.Text.Length > 0)
    {
      ISublines sublines = this.GiveSubline(this.richtextbox, e.Location, this.lastLayerClicked);
      if (sublines == null)
        return;
      if (!this.conditiontooltip.Active || sublines is Item)
      {
        this.conditiontooltip.Active = false;
        foreach (string giveAttribute in sublines.GiveAttributes())
        {
          caption += giveAttribute;
          if (giveAttribute != sublines.GiveAttributes().Last<string>())
            caption += "\n";
        }
        if (sublines.ReturnConditionType() == "parameters")
        {
          string str = caption + "\n";
          List<Param> parameters = this.parameters;
          string type = parameters != null ? parameters.ReturningParameter(sublines.Value)?.Type : (string) null;
          caption = $"{str}Type{type}";
        }
        this.toolTip.SetToolTip((System.Windows.Forms.Control) this.richtextbox, caption);
        this.toolTip.Active = true;
      }
      else
        this.toolTip.Active = false;
    }
    else
      this.toolTip.Active = false;
  }

  private void Layer_MouseDown(object sender, MouseEventArgs e)
  {
    if (e.Button != MouseButtons.Right)
      return;
    this.contextMenuStrip.Items.Clear();
    ToolStripMenuItem toolStripMenuItem1 = new ToolStripMenuItem();
    toolStripMenuItem1.Text = cXMLWizardStringTable.PROPAGETE_LABEL;
    ToolStripMenuItem toolStripMenuItem2 = toolStripMenuItem1;
    toolStripMenuItem2.Click += new EventHandler(this.automaticSplittingToolStripMenuItem_Click);
    ISublines sublines = this.GiveSubline(this.richtextbox, e.Location, this.lastLayerClicked);
    if (sublines != null)
    {
      switch (sublines.ReturnConditionType())
      {
        case "dynamicParameter":
          this.contextMenuStrip.Items.AddRange(new ToolStripItem[1]
          {
            (ToolStripItem) toolStripMenuItem2
          });
          break;
        case "const":
          ToolStripMenuItem toolStripMenuItem3 = new ToolStripMenuItem();
          toolStripMenuItem3.Text = cXMLWizardStringTable.EDIT_NEW_PARAMETER_NAME;
          ToolStripMenuItem toolStripMenuItem4 = toolStripMenuItem3;
          ToolStripMenuItem toolStripMenuItem5 = new ToolStripMenuItem();
          toolStripMenuItem5.Text = cXMLWizardStringTable.FROM_VALUE_LABEL;
          ToolStripMenuItem toolStripMenuItem6 = toolStripMenuItem5;
          ToolStripMenuItem toolStripMenuItem7 = new ToolStripMenuItem();
          toolStripMenuItem7.Text = cXMLWizardStringTable.FROM_NAME_LABEL;
          ToolStripMenuItem toolStripMenuItem8 = toolStripMenuItem7;
          toolStripMenuItem8.Click += new EventHandler(this.EditNewParameter);
          toolStripMenuItem6.Click += new EventHandler(this.EditNewParameter);
          toolStripMenuItem4.DropDownItems.AddRange(new ToolStripItem[2]
          {
            (ToolStripItem) toolStripMenuItem6,
            (ToolStripItem) toolStripMenuItem8
          });
          this.contextMenuStrip.Items.AddRange(new ToolStripItem[2]
          {
            (ToolStripItem) toolStripMenuItem4,
            (ToolStripItem) toolStripMenuItem2
          });
          break;
        default:
          ToolStripMenuItem toolStripMenuItem9 = new ToolStripMenuItem();
          toolStripMenuItem9.Text = cXMLWizardStringTable.EDIT_PARAMETER_LABEL;
          ToolStripMenuItem toolStripMenuItem10 = toolStripMenuItem9;
          ToolStripMenuItem toolStripMenuItem11 = new ToolStripMenuItem();
          toolStripMenuItem11.Text = cXMLWizardStringTable.UNDO_PARAMETER_LABEL;
          ToolStripMenuItem toolStripMenuItem12 = toolStripMenuItem11;
          toolStripMenuItem10.Click += new EventHandler(this.EditNewParameter);
          toolStripMenuItem12.Click += new EventHandler(this.UndoParameter);
          this.contextMenuStrip.Items.AddRange(new ToolStripItem[3]
          {
            (ToolStripItem) toolStripMenuItem2,
            (ToolStripItem) toolStripMenuItem10,
            (ToolStripItem) toolStripMenuItem12
          });
          break;
      }
    }
    else
      this.contextMenuStrip.Items.AddRange(new ToolStripItem[1]
      {
        (ToolStripItem) toolStripMenuItem2
      });
  }

  private void parametersSelectedIndexChanged(object sender, EventArgs e)
  {
    this.lastLayerClicked.Params = this.parameters.ParToStr();
    ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem) sender;
    if (this.ChangeParameter(toolStripMenuItem.Name, this.richtextbox.SelectedText))
    {
      int selectionStart = this.richtextbox.SelectionStart;
      string selectedText = this.richtextbox.SelectedText;
      this.lastLayerClicked.ChangeItems(selectionStart, selectedText, toolStripMenuItem.Name);
      this.richtextbox.Text = this.lastLayerClicked.DetailledCommand;
      this.SetColors(this.richtextbox, this.lastLayerClicked);
      if (!(this.lastLayerClicked.Node.Name == (XName) "DownloadLayer"))
        return;
      this.command.UILayer.ChangeItems(selectionStart, selectedText, toolStripMenuItem.Name);
      ((CUiMainwindow) this.parent).UILayer.RichTextBox.Text = this.command.UILayer.DetailledCommand;
      this.command.SimulationLayer.ChangeItems(selectionStart, selectedText, toolStripMenuItem.Name);
      ((CUiMainwindow) this.parent).SimulationLayer.RichTextBox.Text = this.command.SimulationLayer.DetailledCommand;
    }
    else
    {
      int num = (int) TxMessageBox.Show(cXMLWizardStringTable.PARAMETER_CHANGE, cXMLWizardStringTable.NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private Param SettingParameter(string attribute)
  {
    Param obj = new Param();
    if (this.IsDouble(attribute))
    {
      if (obj.Type == "double" || obj.Type == "int" || obj.Type == null)
      {
        obj.Type = "double";
        if (obj.MaxBound != null && double.Parse(obj.MaxBound) < double.Parse(attribute))
          obj.MaxBound = attribute;
        if (obj.MinBound != null && double.Parse(obj.MinBound) > double.Parse(attribute))
          obj.MinBound = attribute;
        obj.DefaultValue = attribute;
        ((CUiMainwindow) this.parent).Parameter = obj;
      }
    }
    else if (obj.Type == "string" || obj.Type == null)
    {
      obj.Type = "string";
      if (obj.Choices.Count > 0)
      {
        if (!obj.Choices.Contains(attribute))
          obj.Choices.Add(attribute);
      }
      else
        obj.Choices.Add(attribute);
      obj.Choices = obj.Choices;
      obj.DefaultValue = attribute;
      ((CUiMainwindow) this.parent).Parameter = obj;
    }
    return obj;
  }

  private bool ChangeParameter(string parametername, string attribute)
  {
    Param obj = this.parameters.ReturningParameter(parametername);
    if (this.IsDouble(attribute))
    {
      if (!(obj.Type == "double") && !(obj.Type == "int") && obj.Type != null)
        return false;
      obj.Type = "double";
      if (obj.MaxBound != null && double.Parse(obj.MaxBound) < double.Parse(attribute))
        obj.MaxBound = attribute;
      if (obj.MinBound != null && double.Parse(obj.MinBound) > double.Parse(attribute))
        obj.MinBound = attribute;
      obj.DefaultValue = attribute;
      ((CUiMainwindow) this.parent).Parameter = obj;
      return true;
    }
    if (!(obj.Type == "string") && obj.Type != null)
      return false;
    obj.Type = "string";
    if (obj.Choices.Count > 0)
    {
      if (!obj.Choices.Contains(attribute))
        obj.Choices.Add(attribute);
    }
    else
      obj.Choices.Add(attribute);
    obj.Choices = obj.Choices;
    obj.DefaultValue = attribute;
    ((CUiMainwindow) this.parent).Parameter = obj;
    return true;
  }

  private bool IsDouble(string str) => double.TryParse(str, out double _);

  private void Propagate()
  {
    this.lastLayerClicked.AutomaticSplitting(this.richtextbox);
    this.SetColors(this.richtextbox, this.lastLayerClicked);
    if (!(this.lastLayerClicked.Node.Name == (XName) "DownloadLayer"))
      return;
    this.command.UILayer.AutomaticSplitting(((CUiMainwindow) this.parent).UILayer.RichTextBox);
    this.command.SimulationLayer.AutomaticSplitting(((CUiMainwindow) this.parent).SimulationLayer.RichTextBox);
  }

  private void automaticSplittingToolStripMenuItem_Click(object sender, EventArgs e)
  {
    this.Propagate();
  }

  private void UndoParameter(object sender, EventArgs e)
  {
    this.lastLayerClicked.SetAsConst(this.richtextbox.SelectionStart);
    this.SetColors(this.richtextbox, this.lastLayerClicked);
    if (!(this.lastLayerClicked.Node.Name == (XName) "DownloadLayer"))
      return;
    this.command.UILayer.SetAsConst(this.richtextbox.SelectionStart);
    this.command.SimulationLayer.SetAsConst(this.richtextbox.SelectionStart);
  }

  private void EditNewParameter(object sender, EventArgs e)
  {
    if (this.richtextbox.SelectedText.Length != 0)
    {
      bool flag1 = true;
      bool flag2 = false;
      Param parameter = new Param();
      if (((ToolStripItem) sender).Text == cXMLWizardStringTable.FROM_VALUE_LABEL)
      {
        parameter = this.SettingParameter(this.richtextbox.SelectedText);
        flag2 = true;
      }
      else if (((ToolStripItem) sender).Text == cXMLWizardStringTable.FROM_NAME_LABEL)
      {
        parameter.Name = this.richtextbox.SelectedText;
        flag1 = true;
      }
      else if (((ToolStripItem) sender).Text == cXMLWizardStringTable.EDIT_PARAMETER_LABEL)
        parameter = this.command.Params.ReturningParameter(this.GiveSubline(this.richtextbox, this.richtextbox.GetPositionFromCharIndex(this.richtextbox.SelectionStart), this.lastLayerClicked).Value);
      CUiParameterContextMenu parameterContextMenu = new CUiParameterContextMenu()
      {
        Control = this.parent
      };
      parameterContextMenu.ParamConfigurator.ParamConfiguratorCtor(parameter);
      parameterContextMenu.ParamConfigurator.Parameters = this.command.Params;
      this.command.Params.Add(parameter);
      parameterContextMenu.ParamConfigurator.ComboBox.Enabled = flag1;
      parameterContextMenu.ParamConfigurator.TextBox.Enabled = flag2;
      parameterContextMenu.ParamConfigurator.Control = this.parent;
      parameterContextMenu.ParamConfigurator.Parameters = this.parameters;
      if (parameter.Name == "")
        parameterContextMenu.DisableOKButton();
      parameterContextMenu.CommandText = this.richtextbox.Text;
      int num = (int) ((Form) parameterContextMenu).ShowDialog();
      if (parameter.Name == null || !(parameter.Name != ""))
        return;
      string text = this.richtextbox.Text;
      int selectionStart = this.richtextbox.SelectionStart;
      this.richtextbox.Text = text.Remove(this.richtextbox.SelectionStart, this.richtextbox.SelectedText.Length).Insert(selectionStart, parameter.Name);
      this.lastLayerClicked.Params = this.command.Params.ParToStr();
      this.command.UILayer.Params = this.command.Params.ParToStr();
      this.command.SimulationLayer.Params = this.command.Params.ParToStr();
      this.Propagate();
      this.richtextbox.Text = this.lastLayerClicked.DetailledCommand;
    }
    else
    {
      int num1 = (int) TxMessageBox.Show(cXMLWizardStringTable.PARAMETER_SELECT, cXMLWizardStringTable.NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }
}
